"""
This script is used to run all the test of openttd performance
"""
import Process,os,time,  sys,string, math,Analysis, DescriptionParser
from Configuration import Configuration
from threading import Timer
from Performance import Performance
import NetworkCommunication
Configuration = Configuration()

def expEcho(expName, turn, var):
    output = "turn %d"%turn
    if expName == "1a1" :
        output = output + " AIs %d"%var
    if expName == "1a2":
        output = output + "MapSize %d"%math.pow(2,var)
    if expName == "1a3":
        output = output + "number_towns = number_industries = %d"%var
    if expName == "1a4":
        output = output + "max abillity test"
    if expName == "1c":
        output = output + " server"
    return output

def expEcho2(expName, turn, var):
    output = ""
    if expName == "1a1":
        output = "NumOfAIs " + "%d"%var
    if expName == "1a2":
        output = "MapSize %d"%math.pow(2,var)
    if expName == "1a3":
        output = "number_towns = number_industries = %d"%var
    if expName == "1a4":
        output = "AI = 16, MapSize = 2048 * 2048 "
    if expName == "1c":
        output = " server"
    output = output + " Process.maxYear = %d"%Process.maxYear
    return output

def configAtClient(expName, factor):
    Configuration.initExp(expName) 
    Configuration.expVarChange(expName, factor)
#    hostname = Configuration.getHostName()
#    if hostname.find("siqi")<0:
#        path = "/var/tmp/sshen/run/"
#    else:
#        path = "/root/1.0.5_modified/bin/"
#    os.system("cp ../openttd.cfg " + path + "openttd.cfg")
#    os.system("cp ../game_start.scr " + path + "scripts/game_start.scr")

force = True
ip = "node319.das3.tudelft.nl"
def testSingle(expId, expName, maxYear, factor, path = "nullPath", ft="no"):
    print "--------------------------------------------------------------"
    isFT = False
    if ft != "no":
        isFT = True
    turn = totalTurns = 1
    Process.maxYear = maxYear
    address = ""
    localDesktop = False
    if(sys.platform.find("win") >=0):
        Configuration.path = "d:\\tmp"
    else:
        if path == "nullPath":
            path = os.path.join("/var","scratch","sshen","test_result")
            Configuration.removeAutoSave()
        else:
            Process.path = "/root/.openttd/save/autosave"
            localDesktop = True
            path = os.path.join("/var","scratch","sshen","test_result")
            Configuration.removeAutoSave()
            Configuration.path = path
            print "I'm else ", path
    ret = ()
    hostname = Configuration.getHostName()
    if(expName[0:1] == '2' or expName == '5'):
        print hostname, "deciding who I am, a client or a server"
        ret = NetworkCommunication.client()
        print "Network receive ", ret
        if len(ret) == 2:
            address = ret[0]
            if expName[0:1] == '2':
                expName = "3" + expName[1:]
            elif expName[0:1] == '5':
                expName = "6" + expName[1:]
        elif len(ret) == 1 and ret[0] == "server":
            print "I am server"
    if force == True and ip != "" and hostname.find("siqi")>=0:
        expName = "3" + expName[1:]
        address = ip
    print hostname, "now my expName is ", expName
    if os.path.exists(path) == False:
        os.mkdir(path)
    measurement = Performance()
    measurement.flag = 1
    measurement.Configuration = Configuration
    print "the path is " + measurement.Configuration.path
    measurement.initVal(expId, expName, factor)
    measurement.start()
    time.sleep(3)
    
    Analysis.updateSkipList(Process.maxYear)
    path2 = os.path.join(path, expName)
    try:
        if os.path.exists(path2) == False:
            os.mkdir(path2)
    except :
        pass
    filename = Configuration.getExpLog(expId, expName, factor)
    file = open(filename,"w")
    print >>file, 1
    for i in xrange(factor,factor + 1/1):
        starttime = time.time()
        print >> file, "-----------" + time.asctime() + "----------- %d"%expId + "_" + expName + "\n%f"%starttime 
        print >>file , expEcho2(expName, turn, i), " %d"%expId
        if expName == "1c":
            print ""
#            test1c_server.server(i, expId, turn)
        else:
            if sys.platform == "win32":
                os.system("cygwin.bat") 
            else :
#                os.system("mkdir /var/tmp/sshen")
#                os.system("cp -r /home/sshen/run /var/tmp/sshen/")
                binaryPath = Configuration.getBinaryDirectoryPath()
                configAtClient(expName, factor)
                if(expName[0:1] == '2' or expName == "5"):
                    hostname = Configuration.getHostName()
                    os.system("echo "+ hostname+" > serveraddress.txt")
                if (expName[0:1] == '3' or expName == "6"):
                    addon = ""
                    if expName[0:1] == '3':
                        addon = " -v null"
                    address = Configuration.appendAddress(address)
                    if localDesktop == True:
                        cmd = "cd /root/1.0.5_modified/bin/; nohup ./openttd -d 1 -x -n "+ address + "&"
                        os.system(cmd)
                    else:
#                        for cc in range(0, string.atoi(ret[1])):
                        for cc in range(0, 1):
                            os.system("cd " + binaryPath + "; nohup ./openttd" + addon + " -n " + address + "&")
                            time.sleep(2)
                elif expName.find("2a7")>=0:
                    os.system("cd " + binaryPath + "; nohup ./openttd -d 1 -x -D&")
                elif expName == "1a7":
                    os.system("cd " + binaryPath + "; nohup ./openttd -d 1 -D&")
                else:
                    if localDesktop == True:
                        cmd = DescriptionParser.getExecuteableCommands(expName,1 )
                    else :
                        cmd = DescriptionParser.getExecuteableCommands(expName,0)
                    os.system(cmd)
                
        Process.killOpenTTD(file, expId, expName, factor, hostname, Configuration.getPath(), isFT)
        
        endtime = time.time()
        print >> file,"%f"%endtime + "\n-----------" + time.asctime() + "-----------\n"
        file.flush()
        measurement.flag = 0
        measurement.save()
        Analysis.updateSkipList(Process.maxYear)
        Analysis.staticsCPUandMem(expId, expName, 1, totalTurns, factor, factor, Process.maxYear)
#        Analysis.drawCPUGraph(expId, expName, 1, turn, minVars[expName], maxVars[expName], Process.maxYear)
#        Analysis.network(expId, "1c", 1, totalTurns, minVars["1c"], maxVars["1c"], Process.maxYear, True)
        print "end of this script--------------------------------------------------------------"
    
if __name__ == "__main__":
    if len(sys.argv) >= 7:
        testSingle(string.atoi(sys.argv[1]), sys.argv[2], string.atoi(sys.argv[3]), string.atoi(sys.argv[4]), sys.argv[5], sys.argv[6])
    elif len(sys.argv) >= 6:
        testSingle(string.atoi(sys.argv[1]), sys.argv[2], string.atoi(sys.argv[3]), string.atoi(sys.argv[4]), sys.argv[5])
    elif len(sys.argv) >= 5:
        testSingle(string.atoi(sys.argv[1]), sys.argv[2], string.atoi(sys.argv[3]), string.atoi(sys.argv[4]))
    else:
        testSingle(10000, "1a1", 1, 1)  
    
